package org.example.springoauth2.securitycommon.config.resource;

import lombok.AllArgsConstructor;
import org.example.springoauth2.securitycommon.config.PermitAllUrlProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;

/**
 * @author hzq
 * @date 2021/9/13 17:52
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(PermitAllUrlProperties.class)
public class AutoResourceServerConfiguration implements ResourceServerConfigurer {

    private final RemoteTokenServices remoteTokenServices;
    private final PermitAllUrlProperties permitAllUrlProperties;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        UserAuthenticationConverter userTokenConverter = new EnhanceUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userTokenConverter);
        // 增强用户认证转换器
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
        // 使用远程令牌服务
        resources.tokenServices(remoteTokenServices).tokenExtractor(enhanceBearerTokenExtractor());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        permitAllUrlProperties.registryAntMatchers(registry);
        registry.anyRequest().authenticated().and().csrf().disable();
    }

    @Bean
    public EnhanceBearerTokenExtractor enhanceBearerTokenExtractor() {
        return new EnhanceBearerTokenExtractor(permitAllUrlProperties);
    }
}
